package cn.ynu.cmrs.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import cn.ynu.cmrs.R;
import cn.ynu.cmrs.AppConstant;
import cn.ynu.cmrs.MyApplication;
import cn.ynu.cmrs.adapter.CourseAdapter;
import cn.ynu.cmrs.asyncTask.GetInfosTask;
import cn.ynu.cmrs.model.Course;
import cn.ynu.cmrs.model.CourseInfoItem;
import cn.ynu.cmrs.utils.JsonParse;
import cn.ynu.cmrs.utils.WebInterface;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity representing excellent courses
 * 
 * @author starsfury
 */
public class VideoCourseActivity extends Activity implements
		OnItemClickListener {

	/**
	 * Flag indicates whether the user had clicked "see more"
	 */
	private boolean getMoreFlag = false;

	private ListView mListView;
	private View process;
	private View titleBar;
	private TextView titleName;
	/**
	 * The pages of course has displayed
	 */
	private int nowpage = 1;
	/**
	 * The amount of courses
	 */
	private int totalItemsCount = 0;
	/**
	 * The amount of courses has got
	 */
	private int existingItemsCount = 0;
	/**
	 * Retries of request excellent course information
	 */
	private static int retryCount = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		MyApplication.allActivity.add(this);
		this.setContentView(R.layout.courses_list);
		prepareView();
		new GetCoursesTask(this, R.string.fail_general, process).execute();
		mListView.setOnItemClickListener(this);
	}

	private void prepareView() {
		mListView = (ListView) this.findViewById(R.id.courses_listview);
		process = this.findViewById(R.id.progress_courselist);
		titleBar = findViewById(R.id.videocourse_title);
		titleName = (TextView) titleBar.findViewById(R.id.textViewTitle);
		titleName.setText(R.string.vedio_course);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApplication.promptExitApp(this);
		}
		return true;
	}

	/**
	 * AsyncTask class, get all excellent courses from server
	 * 
	 * @author Yasha
	 *
	 */
	private class GetCoursesTask extends GetInfosTask<Void, Course> {

		public GetCoursesTask(Activity mActivity, int mFailMsg, View mView) {
			super(mActivity, mFailMsg, mView);
			// TODO Auto-generated constructor stub
		}

		@Override
		protected Course doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			Map<String, String> param = new HashMap<String, String>();
			param.clear();
			param.put("interface", "getcourse");
			param.put("by", "video");
			param.put("addition", "");
			param.put(
					"start",
					String.valueOf((nowpage - 1)
							* AppConstant.MostUsedConstant.pageSize + 1));
			param.put("amount",
					String.valueOf(AppConstant.MostUsedConstant.pageSize));
			String result = WebInterface.webInterface(param);
			Log.i("courses", result);
			Course courses;
			try {
				courses = JsonParse.getCourse(result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				courses = new Course(null, null, new String[] { "8086",
						mActivity.getString(R.string.inner_error_json) });
			}
			return courses;
		}

		@Override
		protected void onPostExecute(Course result) {
			// TODO Auto-generated method stub
			String[] status = result.getStatus();
			if (status[0].equals("0")) {
				mView.setVisibility(View.GONE);
				doStuffWithResult(result);
			} else {
				if (retryCount < 3) {
					new GetCoursesTask(VideoCourseActivity.this,
							R.string.fail_general, process).execute();
					retryCount++;
				} else {
					mView.setVisibility(View.GONE);
					failMsg(status[1]);
				}
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (nowpage == 1) {
				mView.setVisibility(View.VISIBLE);
			}
		}

		@Override
		protected void doStuffWithResult(Course result) {
			// TODO Auto-generated method stub
			if (nowpage == 1) {
				mView.setVisibility(View.GONE);
				totalItemsCount = result.getHead().getTotalItems();
				existingItemsCount = result.getHead().getAmount();
				Log.i("VideoCourse", result.toString());
				ArrayList<CourseInfoItem> items;
				if (result.getItems() == null) {
					items = new ArrayList<CourseInfoItem>();
				} else {
					items = new ArrayList<CourseInfoItem>(result.getItems());
				}
				CourseAdapter myCourseAdapter = new CourseAdapter(mActivity,
						items, mListView);
				mListView.setAdapter(myCourseAdapter);
			} else {
				existingItemsCount += result.getHead().getAmount();
				ArrayList<CourseInfoItem> items;
				if (result.getItems() == null) {
					items = new ArrayList<CourseInfoItem>();
				} else {
					items = new ArrayList<CourseInfoItem>(result.getItems());
				}
				((CourseAdapter) mListView.getAdapter())
						.addMoreData(new ArrayList<CourseInfoItem>(items));
			}
			//Reset the flag, then can again click on "see more"
			getMoreFlag = false;
			nowpage++;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		if (arg3 == -1) {
			if (!getMoreFlag) {
				if (existingItemsCount >= totalItemsCount) {
					Toast.makeText(VideoCourseActivity.this,
							R.string.no_moreitems, 2).show();
				} else {
					getMoreFlag = true;
					new GetCoursesTask(VideoCourseActivity.this,
							R.string.fail_general, process).execute();
				}
			}
		}
	}

	/**
	 * Launch this Activity from the outside
	 *
	 * @param context context from which Activity should be started
	 */
	public static void launch(Context context) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(context, VideoCourseActivity.class);
		context.startActivity(intent);
	}
}